package com.eudon.design_pattern.behavioral.observer.event_bus;

import java.util.ArrayList;
import java.util.List;

/**
 * @author eudon
 * @description 异步事件监控总线
 * @date 2025/9/2
 * @email syd19970616@gmail.com
 * @address <a href="https://gitee.com/eudon">Gitee</a>
 */
public class AsyncEventBus {
    private final List<Object> observers = new ArrayList<>();

    public void subscribe(Object observer) {
        observers.add(observer);
        EventRegister.registerObserver(observer);
    }

    public void unsubscribe(Object observer) {
        observers.remove(observer);
    }

    public void post(Object event) {
        for (EventAction eventAction : EventRegister.getEventActions(event.getClass())) {
            new Thread(() -> new Runnable() {
                public void run() {
                    try {
                        eventAction.getMethod().invoke(eventAction.getObserver(), event);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }
}
